<template>
  <el-form
    :model="formData"
    :rules="rules"
    ref="formRef"
    label-width="120px"
    class="company-form"
    :disabled="isSubmitting"
  >
    <!-- 公司头像 -->
    <el-form-item label="公司头像" prop="companyAvatar" v-if="isBoss">
      <div class="avatar-container">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :on-change="handleAvatarChange"
          :before-upload="beforeAvatarUpload"
          :auto-upload="false"
        >
          <!-- 头像显示/上传区域 -->
          <img
            v-if="formData.avatarUrl"
            :src="formData.avatarUrl"
            class="avatar"
            alt="公司头像"
          />
          <div v-else class="avatar-placeholder" :class="{ disabled: !isBoss }">
            <i class="el-icon-plus"></i>
            <p>点击上传</p>
          </div>
        </el-upload>
      </div>
    </el-form-item>

    <!-- 公司名称 -->
    <el-form-item label="公司名称" prop="companyName" v-if="isBoss">
      <el-input
        v-model="formData.companyName"
        placeholder="请输入公司名称"
        maxlength="100"
      ></el-input>
    </el-form-item>

    <!-- 创建日期 -->
    <el-form-item label="创建日期" prop="createDate" v-if="isBoss">
      <el-date-picker
        type="date"
        :disabled-date="(time) => time > new Date()"
        placeholder="选择过去的日期"
        v-model="formData.createDate"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        style="width: 400px"
      ></el-date-picker>
    </el-form-item>

    <!-- 公司行业 -->
    <el-form-item label="公司行业" prop="companyIndustry" required>
      <el-autocomplete
        v-model="formData.companyIndustry"
        :fetch-suggestions="queryIndustry"
        placeholder="请输入或选择行业"
        @select="handleIndustrySelect"
        style="width: 100%"
      >
        <template slot-scope="{ item }">{{ item.label }}</template>
      </el-autocomplete>
    </el-form-item>

    <!-- 公司地址 -->
    <el-form-item label="公司地址" prop="location" required>
      <localSelect
        v-model="formData.location"
        :city="formData.location"
      ></localSelect>
    </el-form-item>

    <!-- 工作时间类型 -->
    <el-form-item label="工作时间类型" prop="workTimeType" required>
      <el-select
        v-model="formData.workTimeType"
        placeholder="请选择工作时间类型"
        style="width: 400px"
      >
        <el-option
          v-for="item in workTimeTypeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </el-form-item>

    <!-- 工作日开始时间 -->
    <el-form-item label="工作日开始时间" prop="workDayStartTime" required>
      <el-time-select
        placeholder="选择开始时间"
        v-model="formData.workDayStartTime"
        :picker-options="{
          selectableRange: '18:30:00 - 20:30:00',
        }"
      >
      </el-time-select>
    </el-form-item>

    <!-- 工作日结束时间 -->
    <el-form-item label="工作日结束时间" prop="workDayEndTime" required>
      <el-time-select
        placeholder="选择结束时间"
        v-model="formData.workDayEndTime"
        :picker-options="{
          selectableRange: '18:30:00 - 20:30:00',
        }"
      >
      </el-time-select>
    </el-form-item>

    <!-- 公司介绍 -->
    <el-form-item label="公司介绍" prop="companyIntroduction">
      <el-input
        type="textarea"
        v-model="formData.companyIntroduction"
        :maxlength="500"
        placeholder="请输入公司介绍（最多500字）"
        rows="5"
      ></el-input>
    </el-form-item>

    <!-- 操作按钮 -->
    <el-form-item>
      <el-button type="primary" :loading="isSubmitting" @click="handleSubmit">
        保存信息
      </el-button>
      <el-button @click="handleReset" style="margin-left: 12px">
        重置表单
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {
  editCompanyBasicMessage,
  editCompanyCoreMessage,
  uploadCompanyAvatar,
} from "@/api/recuriter/company";
import localSelect from "@/components/localSelect.vue";
import { getAllCompanyIndustries } from "@/api/recuriter/register";
import { mapGetters } from "vuex";
export default {
  components: { localSelect },
  data() {
    return {
      formData: {},
      workTimeTypeOptions: [
        { value: "SINGLE_REST", label: "单休" },
        { value: "DOUBLE_REST", label: "双休" },
        { value: "FLEXIBLE", label: "弹性工作制" },
      ],
      isSubmitting: false,
      industires: [],
    };
  },

  computed: {
    rules() {
      const baseRules = {
        companyIndustry: [
          { required: true, message: "请输入或选择公司行业", trigger: "blur" },
        ],
        location: [
          {
            required: true,
            message: "请输入公司地址",
            trigger: "change",
          },
        ],
        workTimeType: [
          { required: true, message: "请选择工作时间类型", trigger: "change" },
        ],
        workDayStartTime: [
          {
            required: true,
            message: "请选择工作日开始时间",
            trigger: "change",
          },
        ],
        workDayEndTime: [
          {
            required: true,
            message: "请选择工作日结束时间",
            trigger: "change",
          },
        ],
      };

      if (this.isBoss) {
        return {
          ...baseRules,
          companyName: [{ trigger: ["blur", "change"] }],
          createDate: [{ trigger: "change" }],
          companyAvatar: [],
        };
      } else {
        return baseRules;
      }
    },

    ...mapGetters("recruiter", {
      userInfo: "userInfo",
    }),

    isBoss() {
      if (this.userInfo.type === "BOSS") {
        return true;
      } else {
        return false;
      }
    },
  },

  watch: {
    // 监听userInfo变化，更新表单数据
    userInfo() {
      this.loadFormData();
    },
  },

  methods: {
    loadFormData() {
      const userData = this.userInfo || {};
      let startTime = userData.workDayStartTime.split("T")[1];
      let endTime = userData.workDayEndTime.split("T")[1];
      this.formData = {
        companyName: userData.companyName || "",
        createDate: userData.createDate || "",
        companyIndustry: userData.companyIndustry || "",
        location: userData.location || "",
        workTimeType: userData.workTimeType || "",
        workDayStartTime: startTime || "",
        workDayEndTime: endTime || "",
        companyIntroduction: userData.companyIntroduction || "",
        avatarUrl: userData.companyAvatar + "?t=" + Date.now() || "",
        companyAvatar: null,
      };
    },

    // 头像上传前校验
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("请上传图片文件（JPG/PNG格式）");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过2MB");
        return false;
      }
      return true;
    },

    // 头像校验，预览和存储
    handleAvatarChange(file) {
      if (file.raw && this.beforeAvatarUpload(file.raw)) {
        this.formData.companyAvatar = file.raw;
        const reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = (e) => {
          this.formData.avatarUrl = e.target.result;
          console.log(
            "formData中的companyAvatar类型：",
            this.formData.companyAvatar instanceof File
          );
        };
      } else {
        this.formData.avatarUrl = "";
        this.formData.companyAvatar = null;
      }
    },
    async loadIndustries() {
      try {
        const response = await getAllCompanyIndustries();
        if (response?.data?.code === 201) {
          this.industries = response.data.data.map((industry) => ({
            label: industry.industryName,
            value: industry.industryName,
          }));
        } else {
          this.$message.warning("获取行业列表失败");
        }
      } catch (error) {
        this.$message.error("行业列表加载失败");
        console.error("加载行业失败：", error);
      }
    },

    queryIndustry(queryString, cb) {
      const results = queryString
        ? this.industries.filter((item) =>
            item.label.toLowerCase().includes(queryString.toLowerCase())
          )
        : this.industries;
      cb(results);
    },

    handleIndustrySelect(item) {
      this.formData.companyIndustry = item.value;
    },

    // 表单提交
    async handleSubmit() {
      await this.$refs.formRef.validate();

      const isBoss = this.isBoss;
      const basicData = {};
      const coreData = {};

      basicData.companyIndustry = this.formData.companyIndustry;
      basicData.location = this.formData.location;
      basicData.workTimeType = this.formData.workTimeType;
      basicData.workDayStartTime =
        "2025-07-03T" + this.formData.workDayStartTime;
      basicData.workDayEndTime = "2025-07-03T" + this.formData.workDayEndTime;
      basicData.companyIntroduction = this.formData.companyIntroduction;
      // 只有当填写了公司名称时才添加到提交数据中
      if (this.formData.companyName) {
        coreData.companyName = this.formData.companyName;
      }

      // 只有当选择了创建日期时才添加到提交数据中
      if (this.formData.createDate) {
        coreData.createDate = this.formData.createDate;
      }

      try {
        // 只有上传了头像时才调用头像上传接口
        if (isBoss && this.formData.companyAvatar) {
          console.log("开始调用接口了");
          const avartRes = await uploadCompanyAvatar(
            this.formData.companyAvatar
          );
          console.log("上传了", avartRes);
          if (avartRes.data.code === 201) {
            this.$store.commit("recruiter/SET_TOKEN", avartRes.data.data);
          } else {
            throw new Error("头像上传失败");
          }
        }

        if (isBoss && Object.keys(coreData).length > 0) {
          const coreDatareq = await editCompanyCoreMessage(coreData);
          console.log("接口响应", coreDatareq);
          if (coreDatareq.data.code === 201) {
            this.$store.commit("recruiter/SET_TOKEN", coreDatareq.data.data);
          } else {
            throw new Error("信息提交失败");
          }
        }

        // 修改基本信息
        const basicDatareq = await editCompanyBasicMessage(basicData);
        if (basicDatareq.data.code === 201) {
          this.$store.commit("recruiter/SET_TOKEN", basicDatareq.data.data);
        }

        this.$message.success("信息修改成功");
        this.$router.replace({ name: "company-message" });
        this.handleReset();
      } catch (error) {
        this.$message.error("信息修改失败，请稍后重试");
        console.log("接口调用失败", error);
      } finally {
        this.isSubmitting = false;
      }
    },

    // 重置表单
    handleReset() {
      this.$refs.formRef.resetFields();
      this.formData.avatarUrl = "";
      this.formData.companyAvatar = null;
    },
  },

  mounted() {
    this.loadFormData();
    this.loadIndustries();
  },
};
</script>

<style scoped>
.company-form {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.el-form-item {
  margin-bottom: 18px;
}

.avatar-container {
  position: relative;
  width: 200px;
  height: 200px;
  margin: 0 auto 16px;
}

.avatar-uploader {
  width: 120px;
  height: 120px;
  border: 2px dashed #e0e2e6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-placeholder {
  text-align: center;
}

.avatar-placeholder i {
  font-size: 36px;
  color: #909399;
  margin-bottom: 8px;
}

.avatar-placeholder p {
  font-size: 14px;
  color: #909399;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  display: block;
}

.el-input,
.el-select,
.el-date-editor {
  width: 100% !important;
}

.el-textarea__inner {
  min-height: 120px;
  resize: vertical;
}

/* 按钮加载状态样式 */
.el-button--primary[disabled],
.el-button--primary[aria-disabled="true"] {
  cursor: not-allowed;
  opacity: 0.6;
}

.el-input[disabled],
.el-input[readonly] {
  background-color: #f5f7fa;
  cursor: not-allowed;
  opacity: 0.8;
}
</style>